package com.gopay.bis.manager.bank.ebank;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.pab.ebank.PabB2cMessage;
import com.gopay.common.domain.bank.pab.ebank.PabOrderMessageRes;
import com.gopay.common.domain.bank.pab.ebank.PabQueryOrdersMessageRes;
import com.gopay.common.domain.user.mcc.UserMccTransformReq;
import com.gopay.common.domain.user.mcc.UserMccTransformRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.mcc.manager.UserMccTransformManager;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

public class PabB2cManager implements BankManagerRemoteService {

	private BankService pabB2cBankServiceClientHna;

	private BankService pabB2cBankServiceClient;

	@Resource(name = "pabConfig")
	private Map<String, String> pabConfig;
	
	@Resource(name = "userMccTransformManager")
	private UserMccTransformManager userMccTransformManager;

	@Override
	public Object sign(BaseMessage msg) throws GopayException {
		PabB2cMessage message = (PabB2cMessage) msg;
		/**
		 * 币种
		 */
		message.setCurrency(pabConfig.get("PAB.CURTYPE.CNY"));
		/**
		 * 二级商户代码，若无该代码，则传入00000000 （注意：若有二级商户代码，长度为8位，请左补零至10位传入；不为8位，则正常传入）
		 * 一期的做法是：商户代码传入00000000，商户名称是空格
		 */
		String gopayMccCode = (String) pabConfig.get("PAB.B2C.GOPAY.MCC.CUSTID");
		String[] gopayMccCodeArray = gopayMccCode.split(",");
		Random rand = new Random();
		int num = rand.nextInt(gopayMccCodeArray.length);
		String custId = new String(gopayMccCodeArray[num]);
		UserMccTransformReq userReq = new UserMccTransformReq();
		userReq.setCustId(custId);
		msg.setSendBankCustId(custId);
		UserMccTransformRes userRes = userMccTransformManager.graspUserInfo(userReq);
		if (userRes == null) {
			message.setTermNo("00000000");
			message.setSecondMername(" ");
		} else {
			String termNo = custId;
			if (8 == termNo.length()) {
				termNo = StringUtils.leftPad(custId, 10, '0');
			}
			message.setTermNo(termNo);
			message.setSecondMername(userRes.getCorpName());
		}

		message.setRemark("gopay");
		/**
		 * 订单日期 YYYY-MM-DD
		 */
		Date orderDate = DateUtils.strToDate(message.getOrderDate());
		message.setTradeDate(DateUtils.format(orderDate,"yyyy-MM-dd"));
		message.setVersion(pabConfig.get("PAB.B2C.VERSION"));
		/**
		 * 设置银行订单号
		 */
		message.setBankOrderId(message.getOrderId());
		message.setPlainMessage(buildPlain(message));
		String signMessage = "";
		BankLogUtils.printB2CManagerSignSendLog(message);
		if (message.isHna()) {
			signMessage = (String) pabB2cBankServiceClientHna.sign(message);
		} else {
			signMessage = (String) pabB2cBankServiceClient.sign(message);
		}
		message.setSignMessage(signMessage);
		BankLogUtils.printB2CManagerSignReturnLog(message);
		return message;
	}

	private String buildPlain(PabB2cMessage message) {

		StringBuffer plainData = new StringBuffer();
		/**
		 * 商户代码
		 */
		plainData.append("MechantNo=").append(message.getMerID())
				/**
				 * 订单号
				 */
				.append("&OrderNo=").append(message.getBankOrderId())
				/**
				 * 订单日期 YYYY-MM-DD
				 */
				.append("&OrderDate=").append(message.getTradeDate())
				/**
				 * 订单金额，精确到分(不带千分号、不带逗号)，例如1000.01
				 */
				.append("&PayAmount=").append(message.getAmount())
				/**
				 * 币种，只能为RMB
				 */
				.append("&Currency=").append(message.getCurrency())
				/**
				 * 后台返回地址
				 */
				.append("&ReturnURL=").append(message.getPayRuturnUrl())
				/**
				 * 二级商户代码，若无该代码，则传入00000000
				 * （注意：若有二级商户代码，长度为8位，请左补零至10位传入；不为8位，则正常传入）
				 */
				.append("&TermNo=").append(message.getTermNo())
				/**
				 * 商户结果页面显示地址
				 */
				.append("&JumpURL=").append(message.getPayNotifyUrl())
				/**
				 * 保留字段
				 */
				.append("&ReservedField=").append(message.getRemark())
				/**
				 * 版本号，只能为2.0
				 */
				.append("&Version=").append(message.getVersion());

		BankLogUtils.printB2CSignPlainLog(message);
		return plainData.toString();
	}

	@Override
	public Object verify(BaseMessage msg) throws GopayException {
		boolean flag = false;
		PabOrderMessageRes message=(PabOrderMessageRes)msg;
		message.setPlainMessage(buildverifyB2C(message));
		BankLogUtils.printB2CManagerVerifySendLog(msg);
		if (msg.isHna()) {
			flag = (Boolean) pabB2cBankServiceClientHna.verify(msg);
		} else {
			flag = (Boolean) pabB2cBankServiceClient.verify(msg);
		}
		BankLogUtils.printB2CManagerVerifyReturnLog(msg, flag);
		return flag;
	}

	@Override
	public Object query(Object obj) throws GopayException {
		PabB2cMessage message=(PabB2cMessage)obj;
		BankLogUtils.printB2CManagerQuerySendLog(message, "");
		PabQueryOrdersMessageRes pabQueryRes = new PabQueryOrdersMessageRes();
		message.setPlainMessage(buildQueryB2C(message));
		if(message.isHna()){
			pabQueryRes = (PabQueryOrdersMessageRes) pabB2cBankServiceClientHna.query(obj);
		}else{
			pabQueryRes = (PabQueryOrdersMessageRes) pabB2cBankServiceClient.query(obj);
		}
		pabQueryRes.setOutStlmCd(BankConstants.BANK_LOGO_PAB);
		BankLogUtils.printB2CManagerQueryReturnLog(pabQueryRes);
		return pabQueryRes;
	}

	private String buildQueryB2C(PabB2cMessage message) {

		StringBuffer plainData = new StringBuffer();
		/**
		 * 商户代码
		 */
		plainData.append("MechantNo=").append(message.getMerID())
				/**
				 * 订单号
				 */
				.append("&orderNo=").append(message.getOrderId());

		BankLogUtils.printB2CSignPlainLog(message);
		return plainData.toString();
	}
	private String buildverifyB2C(PabOrderMessageRes message) {
		StringBuffer plainData = new StringBuffer();
		plainData.append ("OrderNo=").append (message.getOrderId())
		.append ("&PayAmount=").append (message.getAmount())
		.append ("&Currency=").append (message.getCurrency())
		.append ("&PayFlag=").append (message.getCommitFlag()) 
		.append("&TranTime=").append(message.getTradeDate());
		BankLogUtils.printB2CSignPlainLog(message);
		return plainData.toString();
	}
	public BankService getPabB2cBankServiceClient() {
		return pabB2cBankServiceClient;
	}

	public void setPabB2cBankServiceClient(BankService pabB2cBankServiceClient) {
		this.pabB2cBankServiceClient = pabB2cBankServiceClient;
	}

	public BankService getPabB2cBankServiceClientHna() {
		return pabB2cBankServiceClientHna;
	}

	public void setPabB2cBankServiceClientHna(BankService pabB2cBankServiceClientHna) {
		this.pabB2cBankServiceClientHna = pabB2cBankServiceClientHna;
	}

	public Map<String, String> getPabConfig() {
		return pabConfig;
	}

	public void setPabConfig(Map<String, String> pabConfig) {
		this.pabConfig = pabConfig;
	}

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}
}
